package com.suxin.shiro.md5;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;

/**
 * @author Tang
 * @classname MyRealm
 * @description [  ]
 * @date 2021/3/20 13:28
 */
public class MyRealm extends AuthorizingRealm {

    /**
     * 授权接口
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("================授权执行==================");
        // 查询数据库
        String username = principals.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 角色
        authorizationInfo.addRoles(Arrays.asList("admin","user"));
        // 资源
        authorizationInfo.addStringPermission("user:*:001");
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = token.getPrincipal().toString();
        String credential = token.getCredentials().toString();
        // 查询数据库
        if ("name".equals(principal)) {
            // 指定 盐值
            return new SimpleAuthenticationInfo(
                    principal,
                    "6cc3c5ea4695e361cffb270ca6016061",
                    ByteSource.Util.bytes("suxin"),
                    this.getName()
            );
        }
        return new SimpleAuthenticationInfo();
    }
}